package org.example.exampreparationtreasure.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.example.exampreparationtreasure.common.CommonResultStatus;
import org.example.exampreparationtreasure.config.JwtConfig;
import org.example.exampreparationtreasure.exception.IncorrectQuestionException;
import org.example.exampreparationtreasure.model.entity.IncorrectQuestionRecord;
import org.example.exampreparationtreasure.service.IncorrectQuestionRecordService;
import org.example.exampreparationtreasure.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 错题记录相关接口。
 * <p>
 * 提供错题记录的分页查询、按分类筛选、添加和删除等 REST 接口。
 * 返回值统一为 {success, data} 结构，便于前端消费。
 * </p>
 */
@RestController
@RequestMapping("/api/incorrect-questions")
public class IncorrectQuestionRecordController {
    
    @Autowired
    private IncorrectQuestionRecordService incorrectQuestionRecordService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtConfig jwtConfig;
    /**
     * 分页查询指定用户的所有错题记录。
     * 
     *
     * @param current 当前页码，默认为1
     * @param size 每页大小，默认为10
     * @return 分页结果
     */
    @GetMapping("/user")
    public ResponseEntity<Map<String, Object>> getIncorrectQuestionsByUser(
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            HttpServletRequest request) {
        String token = request.getHeader(jwtConfig.getHeader());
        Long userId = jwtUtil.getUserIdByToken(token);

        Page<IncorrectQuestionRecord> page = new Page<>(current, size);
        IPage<IncorrectQuestionRecord> result = incorrectQuestionRecordService.getAllIncorrectQuestionsByUser(page, userId);
        
        Map<String, Object> body = new HashMap<>();
        body.put("success", true);
        body.put("data", result);
        return ResponseEntity.ok(body);
    }
    
    /**
     * 分页查询指定用户在指定分类下的错题记录。
     * 
     *
     * @param categoryId 分类ID
     * @param current 当前页码，默认为1
     * @param size 每页大小，默认为10
     * @param includeSubcategories 是否包含子分类，默认为false
     * @return 分页结果
     */
    @GetMapping("/user/category/{categoryId}")
    public ResponseEntity<Map<String, Object>> getIncorrectQuestionsByCategory(
            HttpServletRequest request,
            @PathVariable("categoryId") Long categoryId,
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            @RequestParam(value = "includeSubcategories", defaultValue = "true") Boolean includeSubcategories) {
        String token = request.getHeader(jwtConfig.getHeader());
        Long userId = jwtUtil.getUserIdByToken(token);
        Page<IncorrectQuestionRecord> page = new Page<>(current, size);
        IPage<IncorrectQuestionRecord> result;
        
        if (includeSubcategories) {
            result = incorrectQuestionRecordService.getIncorrectQuestionsByCategoryWithSubcategories(
                    page, userId, categoryId, true);
        } else {
            // 使用新的直接查询方法，基于错题记录表的category_id字段
            result = incorrectQuestionRecordService.getIncorrectQuestionsByCategoryDirect(
                    page, userId, categoryId);
        }
        
        Map<String, Object> body = new HashMap<>();
        body.put("success", true);
        body.put("data", result);
        return ResponseEntity.ok(body);
    }
    
    /**
     * 添加错题记录。
     * 
     * @param request HTTP请求对象，用于获取token
     * @param questionId 题目ID
     * @param mistakeReason 错误原因（可选）
     * @return 操作结果
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> addIncorrectQuestion(
            HttpServletRequest request,
            @RequestParam("questionId") Long questionId,
            @RequestParam(value = "mistakeReason", required = false) String mistakeReason) {
        
        Map<String, Object> body = new HashMap<>();

        try {
            // 从token中获取用户ID
            String token = request.getHeader(jwtConfig.getHeader());
            Long userId = jwtUtil.getUserIdByToken(token);

            boolean success = incorrectQuestionRecordService.addIncorrectQuestion(userId, questionId, mistakeReason);

            body.put("success", success);
            body.put("message", "错题记录添加成功");
            return ResponseEntity.ok(body);

        } catch (NumberFormatException e) {
            throw new IncorrectQuestionException(CommonResultStatus.PARAM_ERROR, "参数格式错误");
        }
    }
    /**
     * 删除错题记录（表示用户已掌握该题）。
     * 
     *
     * @param questionId 题目ID
     * @return 操作结果
     */
    @DeleteMapping("/user/question/{questionId}")
    public ResponseEntity<Map<String, Object>> removeIncorrectQuestion(
            HttpServletRequest request,
            @PathVariable("questionId") Long questionId) {
        String token = request.getHeader(jwtConfig.getHeader());
        Long userId = jwtUtil.getUserIdByToken(token);
        boolean success = incorrectQuestionRecordService.removeIncorrectQuestion(userId, questionId);
        
        Map<String, Object> body = new HashMap<>();
        body.put("success", success);
        body.put("message", "错题记录删除成功");
        return ResponseEntity.ok(body);
    }
    
    /**
     * 修复缺失的 category_id 字段数据（管理员接口）
     * 
     * @return 修复结果
     */
    @PostMapping("/admin/fix-category-ids")
    public ResponseEntity<Map<String, Object>> fixMissingCategoryIds() {
        int fixedCount = incorrectQuestionRecordService.fixMissingCategoryIds();
        
        Map<String, Object> body = new HashMap<>();
        body.put("success", true);
        body.put("message", "数据修复完成");
        body.put("fixedCount", fixedCount);
        return ResponseEntity.ok(body);
    }
}
